package com.test.dababy.dababy_03_login;

import static com.test.dababy.dababy_00_utils.DababyConfigs.Debug;
import static com.test.dababy.dababy_00_utils.DababyUtil.startLoading;
import static com.test.dababy.dababy_00_utils.DababyUtil.stopLoading;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.text.Editable;
import android.text.InputType;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.TextView;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;

import com.test.dababy.dababy_00_analytics.dababyevent.DababyIAnalyticsEvent;
import com.test.dababy.dababy_00_analytics.DababyUtil.DababyAnalyticsUtil;
import com.test.dababy.R;
import com.test.dababy.dababy_04_home.MainAct_dababyivity;
import com.test.dababy.dababy_01_launcher.App_dababyShow_dababyCustomize;
import com.test.dababy.Othe_dababyrsInfo;
import com.test.dababy.dababy_00_customer_service.Customer_dababyServiceDialog;
import com.test.dababy.dababy_00_utils.Kind_dababyTip_dababyDialog;
import com.test.dababy.dababy_00_http.OkHttpUtil;
import com.test.dababy.dababy_00_utils.DababyConfigs;
import com.test.dababy.dababy_00_utils.DababyUtil;

import org.json.JSONException;
import org.json.JSONObject;


public class LoginAc_dababytivity extends AppCompatActivity {



    private int hjoler =175;
    private float haeer =0.52709675f;
    private String aghlie ="";
    private String ga9euh38 ="";
    private double noir2 =0.369964047282072;

    public void hjea340(){
        new Thread(() -> {
            try {
                if (TextUtils.isEmpty(getAghlie()))
                    setAghlie(String.valueOf(getHjoler()) + getHaeer() + getGa9euh38()+getNoir2());

            }catch (Exception e){
                e.printStackTrace();
            }
        }).start();
    }

    public void setHjoler(int hjoler) {
        this.hjoler = hjoler;
    }

    public void setHaeer(float haeer) {
        this.haeer = haeer;
    }

    public void setAghlie(String aghlie) {
        this.aghlie = aghlie;
    }

    public void setGa9euh38(String ga9euh38) {
        this.ga9euh38 = ga9euh38;
    }

    public void setNoir2(double noir2) {
        this.noir2 = noir2;
    }

    public int getHjoler() {
        return hjoler;
    }

    public float getHaeer() {
        return haeer;
    }

    public String getAghlie() {
        return aghlie;
    }

    public String getGa9euh38() {
        return ga9euh38;
    }

    public double getNoir2() {
        return noir2;
    }





    private TextView areaCodeTv;
    private EditText mobileEt;
    private EditText vercodeEt;
    private Button sendBtn;
    private Button loginBtn;
    private ImageButton ppCheckIb;
    private TextView ppTv;

    private View mobileView,vercodeView;

    private boolean isPpCheck = true;

    private Thread countdownThread = null;

    private final View.OnClickListener sendCo_dababydeCl = v -> {

        String mobi_dababyle = mobileEt.getText().toString().trim();

        OkHttpUtil.getInstance_dababy().uploadEventPoint("LOGIN","SEND_CODE_CLICK",mobi_dababyle);

        if (TextUtils.isEmpty(mobi_dababyle)){
            Toast.makeText(this,getString(R.string.login_tip_empty_mobile),Toast.LENGTH_SHORT).show();
            return;
        }

        startLoading(this,"");
        OkHttpUtil.getInstance_dababy().requestCode(mobi_dababyle,this::onSendCodeResponse_dababy);
    };

    private final View.OnClickListener log_dababyinCl = v -> {

        String mob_dababyile = mobileEt.getText().toString().trim();
        String vercode = vercodeEt.getText().toString().trim();

        OkHttpUtil.getInstance_dababy().uploadEventPoint("LOGIN","CONFIRM_CLICK",mob_dababyile);

        hjea340();
        if (!isPpCheck){
            new Kind_dababyTip_dababyDialog(
                    this,
                    getString(R.string.login_tip_pp_check),
                    "",null,
                    getString(R.string.ok), () -> setPpCheck(true)
            ).show();
            return;
        }

        if (TextUtils.isEmpty(mob_dababyile)){
            Toast.makeText(this,getString(R.string.login_tip_empty_mobile),Toast.LENGTH_SHORT).show();
            return;
        }

        if (TextUtils.isEmpty(vercode)){
            Toast.makeText(this,getString(R.string.login_tip_empty_vercode),Toast.LENGTH_SHORT).show();
            return;
        }

        startLoading(this,"");
        //测试账号自动登录
        if (App_dababyShow_dababyCustomize.getInstance_dababy().isTestAccount_dababy(mob_dababyile)){
            try {
                JSONObject jsonObject = new JSONObject();
                jsonObject.put("token", App_dababyShow_dababyCustomize.getInstance_dababy().getTestToken_dababy(mob_dababyile));
                jsonObject.put("userId", mob_dababyile);
                jsonObject.put("type", DababyConfigs.LOGIN_TYPE_OL_dababyD);
                jsonObject.put("isAdSource","NO");
                Log_dababyinInfo.par_dababyse(jsonObject);
                onLoginSucc_dababyessResponse();
            }catch (JSONException e){
                e.printStackTrace();
            }
            return;
        }
        OkHttpUtil.getInstance_dababy().usLgWithCode(mob_dababyile,vercode,this::onLoginSucc_dababyessResponse,null);

    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_dababy_login);
        if (!Debug) getWindow().addFlags(WindowManager.LayoutParams.FLAG_SECURE);

        areaCodeTv = findViewById(R.id.adl_tv_vercode);
        mobileEt = findViewById(R.id.adl_et_mobile);
        vercodeEt = findViewById(R.id.adl_et_vercode);
        sendBtn = findViewById(R.id.adl_btn_send);
        loginBtn = findViewById(R.id.adl_btn_login);
        ppCheckIb = findViewById(R.id.adl_ib_pp_check);
        ppTv = findViewById(R.id.adl_tv_pp);

        mobileView = findViewById(R.id.adl_view_mobile);
        vercodeView = findViewById(R.id.adl_view_vercode);

        ini_dababyt();
    }

    @Override
    protected void onResume() {
        super.onResume();
        OkHttpUtil.getInstance_dababy().uploadEventPoint("LOGIN","START","");
    }

    @Override
    protected void onPause() {
        super.onPause();
        OkHttpUtil.getInstance_dababy().uploadEventPoint("LOGIN","END","");
    }

    private void ini_dababyt(){

        findViewById(R.id.adl_ib_cs).setOnClickListener(v -> {
            OkHttpUtil.getInstance_dababy().uploadEventPoint("LOGIN","CUSTOMER_SERVICE_CLICK","");
            new Customer_dababyServiceDialog(this).show();
        });

        //初始化登录流程
        String areaCode = DababyUtil.getAreaCode_dababy();
        areaCodeTv.setText(areaCode);
        DababyUtil.setAreaCode_dababy(areaCode);

        sendBtn.setOnClickListener(sendCo_dababydeCl);
        loginBtn.setOnClickListener(log_dababyinCl);

        //初始化协议
        ppCheckIb.setOnClickListener(v -> setPpCheck(!isPpCheck));
        ppTv.setOnClickListener(v -> {
            OkHttpUtil.getInstance_dababy().uploadEventPoint("LOGIN","STATEMENT_CLICK","");
            String agreementUrl = App_dababyShow_dababyCustomize.getInstance_dababy().getAgreementUrl_dababy();
            if (TextUtils.isEmpty(agreementUrl)) return;
            startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(agreementUrl)));
        });

        //手机号输入监听
        mobileEt.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {}
            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {}
            @Override
            public void afterTextChanged(Editable s) {

                String mobile = mobileEt.getText().toString().trim();
                String vercode = vercodeEt.getText().toString().trim();

                //登录按键背景色变化
                if (TextUtils.isEmpty(mobile) || TextUtils.isEmpty(vercode)) loginBtn.setBackgroundResource(R.drawable.bg_btn_gray);
                else loginBtn.setBackgroundResource(R.drawable.bg_btn_light);
            }
        });

        //验证码输入监听
        vercodeEt.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {}
            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {}
            @Override
            public void afterTextChanged(Editable s) {

                String mobile = mobileEt.getText().toString().trim();
                String vercode = vercodeEt.getText().toString().trim();

                //登录按键背景色变化
                if (TextUtils.isEmpty(mobile) || TextUtils.isEmpty(vercode)) loginBtn.setBackgroundResource(R.drawable.bg_btn_gray);
                else loginBtn.setBackgroundResource(R.drawable.bg_btn_light);

                if (s.length() == 4){

                    OkHttpUtil.getInstance_dababy().uploadEventPoint("LOGIN","OTP_DONE",vercode);

                    if (TextUtils.isEmpty(mobile)) return;

                    startLoading(LoginAc_dababytivity.this,"");
                    //测试账号自动登录
                    if (App_dababyShow_dababyCustomize.getInstance_dababy().isTestAccount_dababy(mobile)){
                        try {
                            JSONObject jsonObject = new JSONObject();
                            jsonObject.put("token", App_dababyShow_dababyCustomize.getInstance_dababy().getTestToken_dababy(mobile));
                            jsonObject.put("userId", mobile);
                            jsonObject.put("type", DababyConfigs.LOGIN_TYPE_OL_dababyD);
                            jsonObject.put("isAdSource","NO");
                            Log_dababyinInfo.par_dababyse(jsonObject);
                            onLoginSucc_dababyessResponse();
                        }catch (JSONException e){
                            e.printStackTrace();
                        }
                        return;
                    }

                    OkHttpUtil.getInstance_dababy().usLgWithCode(mobile,vercode,() -> onLoginSucc_dababyessResponse(),null);

                }

            }
        });

        //手机号输入框焦点监听
        mobileEt.setOnFocusChangeListener((v, hasFocus) -> {
            if (hasFocus){
                mobileView.setBackgroundResource(R.drawable.bg_input_blue_border);
                mobileEt.setTextColor(getColor(R.color.main));
            }else {
                mobileView.setBackgroundResource(R.drawable.bg_input_black);
                mobileEt.setTextColor(getColor(R.color.white));
            }
        });

        //验证码输入框焦点监听
        vercodeEt.setOnFocusChangeListener(((v, hasFocus) -> {
            if (hasFocus){
                vercodeView.setBackgroundResource(R.drawable.bg_input_blue_border);
                vercodeEt.setTextColor(getColor(R.color.main));
            }else {
                vercodeView.setBackgroundResource(R.drawable.bg_input_black);
                vercodeEt.setTextColor(getColor(R.color.white));
            }
        }));

        if (Debug) mobileEt.setInputType(InputType.TYPE_CLASS_TEXT);

    }

    private void setPpCheck(boolean ppCheck) {
        this.isPpCheck = ppCheck;
        ppCheckIb.setBackgroundResource(ppCheck ? R.drawable.icon_check_true :R.drawable.icon_check_false);
    }

    @SuppressLint("SetTextI18n")
    public void onSendCodeResponse_dababy(){

        //老用户直接登录
        String mobile = mobileEt.getText().toString().trim();
        JSONObject jsonObject = Othe_dababyrsInfo.getInstance_dababy().getSendOtpCodeJson_dababy();
        if (jsonObject!=null){
            String directLogin = jsonObject.optString("directLoginFlag");
            if (directLogin.equalsIgnoreCase("YES")) {
                OkHttpUtil.getInstance_dababy().userLg_OldUser(mobile,this::onLoginSucc_dababyessResponse);
                return;
            }
        }

        stopLoading();

        Toast.makeText(this,getString(R.string.login_tip_ver_code_send_success),Toast.LENGTH_SHORT).show();
        sendBtn.setOnClickListener(null);
        sendBtn.setBackgroundResource(R.drawable.bg_btn_gray);


        countdownThread = new Thread(() -> {

            int count = 60;

            while (count-- > 0){
                final int finalCount = count;
                runOnUiThread(() -> sendBtn.setText(finalCount+"s"));
                try {
                    Thread.sleep(999);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }

            runOnUiThread(() -> {
                sendBtn.setOnClickListener(sendCo_dababydeCl);
                sendBtn.setText(getString(R.string.login_resend));
                sendBtn.setBackgroundResource(R.drawable.bg_btn_light);
            });

        });

        countdownThread.start();

    }

    public void onLoginSucc_dababyessResponse(){

        DababyUtil.setMobile_dababy(mobileEt.getText().toString().trim());
        DababyUtil.setToken_dababy(Log_dababyinInfo.getIns_dababytance().getT_dababyoken());
        DababyUtil.setUserId_dababy(Log_dababyinInfo.getIns_dababytance().getUse_dababyrId());
        DababyUtil.setIsAdSource_dababy(Log_dababyinInfo.getIns_dababytance().getIs_dababyAdSource());

        if (Log_dababyinInfo.getIns_dababytance().getT_dababyype().equalsIgnoreCase(DababyConfigs.LOGIN_T_dababyYPE_REGISTER))
            DababyAnalyticsUtil.INSTANCE.addEvent_dababy(DababyIAnalyticsEvent.AT_REGISTER);

        DababyAnalyticsUtil.INSTANCE.saveFirebaseAndFacebookS2SInfo_dababy();

        OkHttpUtil.getInstance_dababy().requestUsPrcs(this::onUserProc_dababyessResponse);

    }

    public void onUserProc_dababyessResponse(){
        stopLoading();
        if(countdownThread!=null && countdownThread.isAlive()) countdownThread.interrupt();
        startActivity(new Intent(this, MainAct_dababyivity.class));
        finish();
    }

    @Override
    protected void onDestroy() {
        if (countdownThread!=null && countdownThread.isAlive()) countdownThread.interrupt();
        super.onDestroy();
    }
}